package com.kool.kauth.controller;

import com.kool.kauth.common.bean.ObjectResult;
import com.kool.kauth.common.bean.Result;
import com.kool.kauth.common.util.ResultUtil;
import com.kool.kauth.request.*;
import com.kool.kauth.service.AuthService;
import com.kool.kauth.vo.TopicAuthResp;
import com.kool.kauth.vo.UserAuthResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * @author : luyu
 * @date :2021/3/24 19:06
 */
@RestController
@Slf4j
public class AuthController {
    @Resource
    private AuthService authService;

    /**
     * 新增或更新用户
     *
     * @param request
     * @return
     */
    @PostMapping("/setUser")
    public Result setUser(@RequestBody @Valid SetUserReq request) {
        authService.setUser(request);
        return ResultUtil.success();
    }

    /**
     * 删除用户
     *
     * @param request
     * @return
     */
    @PostMapping("/deleteUser")
    public Result deleteUser(@RequestBody @Valid DeleteUserReq request) {
        authService.deleteUser(request);
        return ResultUtil.success();
    }

    /**
     * 用户验证
     *
     * @param request
     * @return
     */
    @PostMapping("/userAuth")
    public ObjectResult<UserAuthResp> userAuth(@RequestBody @Valid UserAuthReq request) {
        return ResultUtil.success(authService.userAuth(request));
    }

    /**
     * 授权主题
     *
     * @param request
     * @return
     */
    @PostMapping("/topicPermit")
    public Result topicPermit(@RequestBody @Valid TopicPermitReq request) {
        authService.topicPermit(request);
        return ResultUtil.success();
    }

    /**
     * 主题鉴权
     *
     * @param request
     * @return
     */
    @PostMapping("/topicAuth")
    public ObjectResult<TopicAuthResp> topicAuth(@RequestBody @Valid TopicAuthReq request) {
        return ResultUtil.success(authService.topicAuth(request));
    }

    /**
     * 同步用户
     *
     * @return
     */
    @PostMapping("/syncMqttUsers")
    public Result syncMqttUsers(@RequestBody @Valid SyncMqttUsersReq request) {
        new Thread(() -> {
            try {
                authService.syncMqttUsers(request);
            } catch (Throwable e) {
                log.error(e.getMessage(), e);
            }
        }).start();
        return ResultUtil.success();
    }

    /**
     * 同步主题权限
     *
     * @return
     */
    @PostMapping("/syncTopicPermits")
    public Result syncTopicPermits(@RequestBody @Valid SyncTopicPermitsReq request) {
        new Thread(() -> {
            try {
                authService.syncTopicPermits(request);
            } catch (Throwable e) {
                log.error(e.getMessage(), e);
            }
        }).start();
        return ResultUtil.success();
    }


}
